package com.example.service;

import com.example.model.entity.Follow;
import com.example.model.entity.User;
import com.example.model.entity.Message;
import com.example.repository.FollowRepository;
import com.example.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class FollowService {
    @Autowired
    private FollowRepository followRepository;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MessageRepository messageRepository;

    @Transactional
    public void follow(Long followerId, Long followingId) {
        if (followerId.equals(followingId)) {
            throw new RuntimeException("不能关注自己");
        }
        
        if (followRepository.existsByFollowerIdAndFollowingId(followerId, followingId)) {
            throw new RuntimeException("已经关注过了");
        }
        
        User follower = userService.findById(followerId);
        User following = userService.findById(followingId);
        
        Follow follow = new Follow();
        follow.setFollower(follower);
        follow.setFollowing(following);
        follow.setCreatedAt(LocalDateTime.now());
        
        followRepository.save(follow);
        
        Message message = new Message();
        message.setFromUser(follower);
        message.setToUser(following);
        message.setType("follow");
        message.setContent("关注了你");
        message.setCreatedAt(LocalDateTime.now());
        messageRepository.save(message);
    }

    @Transactional
    public void unfollow(Long followerId, Long followingId) {
        followRepository.deleteByFollowerIdAndFollowingId(followerId, followingId);
    }

    public boolean hasFollowed(Long followerId, Long followingId) {
        return followRepository.existsByFollowerIdAndFollowingId(followerId, followingId);
    }
} 